﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tenmah.BusinessLogic.BusinessEntities;
using Tenmah.DataAccess;

namespace Tenmah.BusinessLogic
{
    public class TestModel:Test
    {
        private int currentQuestion = 0;

        public TestModel(int id)
            : base(TestDBAccessor.GetTest(id))
        {
        }

        public TestModel(int id, string name, string path, string teacherLogin, QuestionCollection questions)
            : base(id, name, path, teacherLogin, questions)
        {
        }

        public TestModel(Test test): base(test)
        {
        }

        public int CurrentQuestion
        {
            get { return this.currentQuestion; }
        }

        public Question NextQuestion()
        {
            if (currentQuestion < this.QuestionsCount)
                return this.Questions[currentQuestion++];
            else
                return null;
        }

        public void Reload()
        {
            this.Load(this.Id);
        }

        public void Load(int id)
        {
            this.Copy(TestDBAccessor.GetTest(id));
            this.currentQuestion = 0;
        }

        public void ProcessUserAnswers(UserAnswerCollection userAnswers, int userID)
        {
            int userPoints = 0;
            int questionNumber = 0;
            foreach (Question question in this.Questions)
            {
                UserAnswer currentQuestionAnswers = userAnswers[questionNumber++];
                int answerNumber = 0;
                foreach (Answer answer in question.Answers)
                {
                    if (currentQuestionAnswers[answerNumber++] == true)
                    {
                        userPoints += answer.Points;
                    }
                }
            }
            TestDBAccessor.SaveTestResults(userID, this.Id, userPoints);
        }
    }
}
